<?php

abstract class Engine_Form_Grid {

	protected $rowset = null;
    protected $columns = array();
    protected $actions = array();

    abstract protected function init();

	public function __construct($adapter, $header = null) {
		$this->rowset  = $adapter->getRowset();
        $this->init();
	}

	public function render() {
        $this->actions;
		$rowset = $this->rowset;
		$result = '';
		if ($rowset && is_array($rowset)) {

			$result .= '<table class="table table-striped">';
			//table header
			$result .= '<thead><tr>';
			foreach ($this->columns as $column) {
				$result .= '<th>' . $column->getName() . '</th>';
			}

            if (!empty($this->actions)) {
                $result .= '<th>&nbsp;</th>';
            }

			$result .= '</thead></tr>';
			$result .= '<tbody>';
			foreach ($rowset as $id => $row) {
				$result .= '<tr>';
				foreach ($this->columns as $column) {
					$result .= '<td>' . $row[$column->getField()] . '</td>';
				}
                if (!empty($this->actions)) {
                    $result .= '<td>' . $this->renderActions($row) . '</td>';;
                }
				$result .= '</tr>';
            }
			$result .= '</tbody>';
			$result .= '</table>';
		}
		return $result;
	}

    public function addAction(Engine_Grid_Action $action) {
        $this->actions[$action->getName()] = $action;
    }

    public function removeAction(Engine_Grid_Action $action) {
        $this->actions[$action->getName()] = $action;
    }

    public function addColumn(Engine_Grid_Column $column) {
        $this->columns[$column->getName()] = $column;
    }

    public function removeColumn($name) {
        if (array_key_exists($name, $this->columns))
        unset ($this->columns[$name]);
    }

    public function renderActions($data){
        $result = '';
        if (!empty($this->actions)) {
            foreach ($this->actions as $action) {
                $result .= '<a href="' . $action->prepareHref($data) . '">' . $action->getName() .'</a><br>';
            }
        }
        return $result;
    }
}